/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * HTML generation program that shows a table of multiplication results
 * based on what the user inputs. 
 * @author Alexander Lazarz
 */
public class MultiplicationServlet extends HttpServlet {

    private String userName;
    private String password;
    private String titleString;
    private int numrows;
    private int numcols;

    private enum LOGIN {

        LOGGED_IN, NOT_LOGGED_IN, RUN_AGAIN
    };
    private LOGIN loggedin;

    public MultiplicationServlet() {
        userName = "";
        password = "";
        titleString = "";
        numrows = 0;
        numcols = 0;
    }

    /**
     * Generates the page where you enter the number of rows and columns you
     * want shown in the multiplication table.
     * @param req Request packet forwarded by the servlet.
     * @param res Response packet also forwarded by the servlet.
     * @param validateLogin - Unused parameter.
     * @throws IOException In case something goes wrong with I/O.
     */
    private void doFormPage(HttpServletRequest req, HttpServletResponse res, 
            boolean validateLogin) throws IOException {
        PrintWriter out = res.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Alex's Tables of Multiplication</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h2>" + titleString + "</h2>");
        out.println("<br />");
        out.println("<form action=\"http://localhost:8080/173webapp\""
                + " method=\"post\">");
        out.println("<input type=\"text\" name=\"numrows\" id=\"numrows\""
                + " value=\"Enter the number of rows for the table.\">"
                + "<br />");
        out.println("<input type=\"text\" name=\"numcols\" id=\"numcols\""
                + " value=\"Enter the number of columns for the table.\">"
                + "<br />");
        out.println("<input type=\"submit\" value=\"Submit Entries\">"
                + "<br />");
        out.println("<input type=\"hidden\" name=\"state\" "
                + "value=\"LOGGED_IN\"");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
    }

    /**
     * doGet - Launches the entire process by grabbing the first request
     * packet sent by the client, and forwarding it to doLoginPage.
     * @param req The client's request packet, generated with information
     * from the client and created by the servlet.
     * @param res The servlet's response packet.
     * @throws IOException In case something goes wrong with I/O.
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws IOException {
        doLoginPage(req, res);
    }
    
    /**
     * doPost - The method at the center of all this application's operations.
     * Interprets information sent to it, and decides where the user will go
     * by using states and information provided in the web.xml file, like
     * username and password.
     * @param req Request packet forwarded by the servlet.
     * @param res Response packet forwarded by the servlet.
     * @throws IOException
     * @throws ServletException 
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException {

        if (req.getParameter("state").equals("RUN_AGAIN")) {
            loggedin = LOGIN.RUN_AGAIN;
        } else if (req.getParameter("state").equals("LOGGED_IN")) {
            loggedin = LOGIN.LOGGED_IN;
        } else if (req.getParameter("state").equals("NOT_LOGGED_IN")) {
            loggedin = LOGIN.NOT_LOGGED_IN;
        }

        switch (loggedin) {


            case RUN_AGAIN:
                doFormPage(req, res, true);
                break;

            case NOT_LOGGED_IN:
                if (req.getParameter("username").equals(userName)) {
                    if (req.getParameter("password").equals(password)) {
                        doFormPage(req, res, true);
                    } else {
                        doLoginPage(req, res, true, false);
                    }
                } else {
                    if (req.getParameter("password").equals(password)) {
                        doLoginPage(req, res, false, true);
                    } else {
                        doLoginPage(req, res, false, false);
                    }
                }
                break;

            case LOGGED_IN:
                numrows = Integer.parseInt(req.getParameter("numrows"));
                numcols = Integer.parseInt(req.getParameter("numcols"));

                doResultsPage(req, res);
                break;
        }
    }

    /**
     * doLoginPage - Creates and displays the HTML for the login page.
     * @param req Request packet forwarded by the servlet.
     * @param res Response packet forwarded by the servlet.
     * @throws IOException In case something goes wrong with I/O.
     */
    private void doLoginPage(HttpServletRequest req, HttpServletResponse res)
            throws IOException {
        PrintWriter out = res.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Alex's Tables of Multiplication</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h2>" + titleString + "</h2>");
        out.println("<br />");
        out.println("<form action=\"http://localhost:8080/173webapp\""
                + " method=\"post\">");
        out.println("<input type=\"text\" name=\"username\" "
                + "id=\"username\""
                + " value=\"Enter your username.\"><br />");
        out.println("<input type=\"text\" name=\"password\" "
                + "id=\"password\""
                + " value=\"Enter your password.\"><br />");
        out.println("<input type=\"submit\" value=\"Login\"><br />");
        out.println("<input type=\"hidden\" name=\"state\""
                + " value=\"NOT_LOGGED_IN\"");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
    }

    /**
     * doLoginPage - Overloaded method in case the user failed 
     * the login check.
     * This will spew an error message next to the two text boxes for
     * username and password based on what the user got wrong.
     * @param req Request packet forwarded by the servlet.
     * @param res Response packet forwarded by the servlet.
     * @param userNameCorrect - Boolean check for if they messed up the
     * username.
     * @param passwordCorrect - Boolean check for if they messed up the
     * password.
     * @throws IOException In case something goes wrong with I/O!
     */
    private void doLoginPage(HttpServletRequest req, HttpServletResponse res, 
            boolean userNameCorrect, boolean passwordCorrect) 
            throws IOException {
        PrintWriter out = res.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Alex's Tables of Multiplication</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h2>" + titleString + "</h2>");
        out.println("<br />");
        out.println("<form action=\"http://localhost:8080/173webapp\" "
                + "method=\"post\">");
        if (userNameCorrect == false) {
            out.println("<input type=\"text\" name=\"username\" "
                    + "id=\"username\" value=\"Enter your username.\"> "
                    + "Username Incorrect."
                    + "<br />");
        } else {
            out.println("<input type=\"text\" name=\"username\""
                    + " id=\"username\"value=\"Enter your username.\">"
                    + "<br />");
        }
        if (passwordCorrect == false) {
            out.println("<input type=\"text\" name=\"password\""
                    + " id=\"password\" value=\"Enter your password.\">"
                    + " Password Incorrect.<br />");
        } else {
            out.println("<input type=\"text\" name=\"password\" "
                    + "id=\"password\" value=\"Enter your password.\">"
                    + "<br />");
        }
        out.println("<input type=\"submit\" value=\"Login\"><br />");
        out.println("<input type=\"hidden\" name=\"state\" "
                + "value=\"NOT_LOGGED_IN\"");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
    }

    /**
     * doResultsPage - Generates the HTML for the page that shows off the
     * multiplication table. Takes the numrows and numcols variables sent
     * by the Form page, and loops through them to build the table.
     * @param req - Request packet forwarded by the servlet.
     * @param res - Response packet forwarded by the servlet.
     * @throws IOException In case something goes wrong with I/O.
     */
    private void doResultsPage(HttpServletRequest req, 
            HttpServletResponse res) 
            throws IOException {
        PrintWriter out = res.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Alex's Tables of Multiplication</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h2>" + titleString + "</h2>");

        if (numrows > 100 | numrows < 1) {
            out.println("Your number of rows is WAY too high. "
                    + "Between 1 and 100 please!<br />");
        }

        if (numcols > 100 | numcols < 1) {
            out.println("Your number of columns is WAY too high. "
                    + "Between 1 and 100 please!");
        }

        if (numrows <= 100 & numrows >= 1) {
            if (numcols <= 100 & numcols >= 1) {
                out.println("<br />");
                out.println("<table>");
                for (int r = 1; r <= numrows; r++) {
                    out.println("<tr>");
                    for (int c = 1; c <= numcols; c++) {
                        if (r == 1) {
                            out.println("<td>" + c + "</td>");
                        } else {
                            out.println("<td>" + (r * c) + "</td>");
                        }
                    }
                    out.println("</tr>");
                }
                out.println("<br />");
            }
        }
        out.println("<form action=\"http://localhost:8080/173webapp\" "
                + "method=\"post\">");
        out.println("<input type=\"submit\" value=\"Do Another\">");
        out.println("<input type=\"hidden\" name=\"state\" "
                + "value=\"RUN_AGAIN\"");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
    }

    /**
     * getServletInfo - Just returns a bit of info about the servlet.
     * @return A string talking about the servlet and who wrote it.
     */
    @Override
    public String getServletInfo() {
        return "A quick servlet written by Alex Lazarz.";
    }

    /**
     * init - Grabs necessary information from web.xml which is used in the
     * login process, as well as displaying the title string on every page.
     * @param config Object referencing the web.xml file.
     * @throws ServletException In case something breaks inside the servlet.
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        userName = config.getInitParameter("username");
        password = config.getInitParameter("password");
        titleString = config.getInitParameter("titleString");
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet MultiplicationServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet MultiplicationServlet at " + 
                    request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }
}
